import os
from elasticsearch import Elasticsearch
import json

# extract from tmdb.json
def extract_from_tmdb(tmdb_file):
    movies = []
    with open(tmdb_file, 'r') as f:
        data = json.load(f)
        for id in data:
            movie = data[id]
            movies.append(movie)
    return movies


client = Elasticsearch(
    "https://localhost:9200/",
    basic_auth=("elastic", os.environ["ELASTIC_PASSWORD"]),
    ssl_assert_fingerprint=os.environ["ELASTIC_CERT_FINGERPRINT"],
)

# info = client.info()

movies = extract_from_tmdb('tmdb.json')
# create index movies
client.indices.create(index="movies")
def index_movies(movies):
    for movie in movies:
        client.index(index="movies", document=movie, id=movie["id"])
        print(movie["title"] + " indexed.")

def bulk_index_movies(movies):
    actions = []
    for movie in movies:
        actions.append({
            "create": {
                "_index": "movies",
                "_id": movie["id"],
            }
        })
        actions.append(movie)
    client.bulk(index="movies", operations=actions)
    print("Bulk indexing completed.")

bulk_index_movies(movies)